/*
 * @FileName: [OrganizationController.java]
 * 
 * @Package com.bcinfo.upp.admin.ac.controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO Technology Limited Company ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 42 $ $LastChangedDate: 2013-10-12 10:19:36 +0800 (星期六, 12 十月 2013) $ $LastChangedBy: wanggc $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author $Author: wanggc $
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bcinfo.iccard.admin.ac.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bcinfo.iccard.admin.common.ModuleEnum;
import com.bcinfo.iccard.admin.controller.AbstractController;
import com.bcinfo.upp.ac.model.Organization;
import com.bcinfo.upp.ac.service.OrganizationService;
import com.bcinfo.upp.ac.util.AcConstant;
import com.bcinfo.upp.exception.UppException;

/**
 * 组织管理后台控制器<br/>
 * <p>
 * Description:<br/>
 * <p>
 * 包含以下功能：<br/>
 * 新增组织 <br/>
 * 修改组织 <br/>
 * 删除组织<br/>
 * 查询组织(树形异步加载) <br/>
 * 查询组织详细
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *      /ac/organization/toAddView
 * </PRE>
 * <p>
 */

@Controller
@RequestMapping("/ac/organization")
public class OrganizationController extends AbstractController
{
    @Autowired
    private OrganizationService _organizationService;

    private final static Logger _logger = Logger.getLogger(OrganizationController.class);

    /**
     * 点击菜单组织机构，跳转进入组织管理页面 <br/>
     * <p>
     * Description:跳转进入组织管理页面 <br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午10:50:37<br/>
     * <p>
     * 
     * @return
     * 
     */
    @RequestMapping("/toListView")
    public ModelAndView toListView()
    {
        return new ModelAndView("ac/org/org_list_tree");
    }

    /**
     * 获取组织机构TREE型列表（异步加载） <br/>
     * <p>
     * Description: 根据传入的ID,加载该ID下的子信息 <br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午11:25:21<br/>
     * <p>
     * 
     * @param request
     * @param response
     * @return 以ajax方式返回处理结果，格式为map结构
     * 
     */
    @RequestMapping("/list")
    @ResponseBody
    public List<Map<String, String>> list(String id)
    {
        String treeId = "0"; // 组织树ID，0表示默认为根节点
        if (StringUtils.isNotBlank(id))
        {
            treeId = id;
        }
        List<Organization> list = null;
        try
        {
            list = _organizationService.listSubOrg(new Long(treeId));
            addLog(ModuleEnum.Org.view, "operatorId=" + id + "|desc=查询组织列表成功");
        }
        catch (Exception e)
        {
            handleException(e);
            addLog(ModuleEnum.Org.view, "operatorId=" + id + "|desc=查询组织列表失败");
        }

        // 以下操作是把返回的接口List<Organization>数据转换成List<Map<String,String>>，因为在ZTree框架中，只认识id，pid,name,isParent
        List<Map<String, String>> backList = new ArrayList<Map<String, String>>();

        if (null != list && !list.isEmpty())
        {
            String refreshFlag = String.valueOf(System.currentTimeMillis());
            for (Organization org : list)
            {
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", String.valueOf(org.getOrgId()));
                map.put("pid", String.valueOf(org.getParentOrgId()));
                map.put("name", org.getOrgName());
                map.put("isParent", org.getIsTrunk());
                map.put("refreshFlag", refreshFlag);
                backList.add(map);
            }
        }
        return backList;
    }

    /**
     * 点击Add组织机构，跳转进入组织机构新增页面 <br/>
     * <p>
     * Description: 跳转进入组织机构新增页面<br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午10:52:17<br/>
     * <p>
     * 
     * @param request
     * @param response
     * @return
     * 
     */
    @RequestMapping("/toAddView")
    public ModelAndView toAddView()
    {
        Long id = new Long(request.getParameter("id"));
        Organization organization = new Organization();
        organization.setParentOrgId(id);
        return new ModelAndView("ac/org/org_add", "organization", organization);
    }

    /**
     * 添加一条组织机构 <br/>
     * <p>
     * Description: 根据传入的组织ID，在该ID下添加一条子信息 <br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午10:53:01<br/>
     * <p>
     * 
     * @param request
     * @param organization
     * @return 以ajax方式返回处理结果，格式为map结构
     * 
     */
    @RequestMapping("/add")
    @ResponseBody
    public Map<String, String> add(Organization organization)
    {
        Map<String, String> map = new HashMap<String, String>();
        if (null != organization)
        {
            organization.setCreateTime(new Timestamp(System.currentTimeMillis()));
            organization.setStatus(AcConstant.VALID);
            try
            {
                Long backId = _organizationService.add(organization);
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                        ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
                map.put("id", String.valueOf(backId));
                map.put("pid", String.valueOf(organization.getParentOrgId()));
                addLog(ModuleEnum.Org.add, "operatorId=" + backId + "|desc=新增组织成功,返回的operatorID为新增后的子栏目ID");
            }
            catch (UppException e)
            {
                map = packageUppException(e);
                addLog(ModuleEnum.Org.add, "operatorId=" + organization.getParentOrgId()
                        + "|desc=新增组织失败；UppDataBaseException异常;返回为该栏目ID");

            }
            catch (Exception e)
            {
                map = packageException(e);
                addLog(ModuleEnum.Org.add, "operatorId=" + organization.getParentOrgId()
                        + "|desc=新增组织失败；UppDataBaseException异常;返回为该栏目ID");
            }
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_WARN, null, "传入参数为空");
        }

        return map;
    }

    /**
     * 选中某一个组织结构，点击Edit，跳转进入组织机构信息修改页面 <br/>
     * <p>
     * Description: 跳转进入组织机构信息修改页面<br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午10:53:57<br/>
     * <p>
     * 
     * @param request
     * @param response
     * @return
     * 
     */
    @RequestMapping("/toEditView")
    public ModelAndView toEditView()
    {
        ModelAndView mav = new ModelAndView("ac/org/org_edit");
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id))
        {
            Organization organization = null;
            try
            {
                organization = _organizationService.findById(new Long(id));
                addLog(ModuleEnum.Org.view, "operatorId=" + id + "|desc=查询一条修改组织信息成功");
            }
            catch (Exception e)
            {
                handleException(e);
                addLog(ModuleEnum.Org.view, "operatorId=" + id + "|desc=查询一条修改组织信息失败");
                mav.addObject("message", "操作失败");
                return mav;
            }
            mav.addObject("organization", organization);

            return mav;
        }
        else
        {
            mav.addObject("message", "Error:未选中树形中的组织");
            return mav;
        }
    }

    /**
     * 修改一条组织机构<br/>
     * <p>
     * Description: 根据传入选中的组织信息，修改该组织信息 <br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午10:54:48<br/>
     * <p>
     * 
     * @param request
     * @param organization
     * @return 以ajax方式返回处理结果，格式为map结构
     * 
     */
    @RequestMapping("/update")
    @ResponseBody
    public Map<String, String> update(Organization organization)
    {
        Map<String, String> map = new HashMap<String, String>();
        if (null != organization)
        {
            organization.setLastModifiedTime(new Timestamp(System.currentTimeMillis()));
            organization.setStatus(AcConstant.VALID);
            try
            {
                _organizationService.update(organization);
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                        ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
                map.put("id", String.valueOf(organization.getOrgId()));
                map.put("pid", String.valueOf(organization.getParentOrgId()));
                addLog(ModuleEnum.Org.update, "operatorId=" + organization.getOrgId() + "|desc=修改一条修改组织信息成功");
            }
            catch (UppException e)
            {
                map = packageUppException(e);
                addLog(ModuleEnum.Org.update, "operatorId=" + organization.getOrgId() + "|desc=修改一条修改组织信息失败");

            }
            catch (Exception e)
            {
                map = packageException(e);
                addLog(ModuleEnum.Org.update, "operatorId=" + organization.getOrgId() + "|desc=修改一条修改组织信息失败");
            }
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_WARN, null, "传入参数为空");
        }

        return map;
    }

    /**
     * 删除一条组织机构 <br/>
     * <p>
     * Description: 删除选中的组织<br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午10:55:37<br/>
     * <p>
     * 
     * @param request
     * @param organization
     * @return 以ajax方式返回处理结果，格式为map结构
     * 
     */
    @RequestMapping("/remove")
    @ResponseBody
    public Map<String, String> remove(Organization organization)
    {
        Map<String, String> map = new HashMap<String, String>();
        if (null != organization)
        {
            try
            {
                _organizationService.delete(organization.getOrgId());
                map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                        ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
                map.put("pid", String.valueOf(organization.getParentOrgId()));
                addLog(ModuleEnum.Org.remove, "operatorId=" + organization.getOrgId() + "|desc=删除一条修改组织信息成功");
                if (_logger.isInfoEnabled())
                {
                    _logger.info("operatorId=" + organization.getOrgId() + "|desc=删除一条修改组织信息成功");
                }
            }
            catch (UppException e)
            {
                map = packageUppException(e);
                addLog(ModuleEnum.Org.remove, "operatorId=" + organization.getOrgId() + "|desc=删除一条修改组织信息失败");

            }
            catch (Exception e)
            {
                map = packageException(e);
                addLog(ModuleEnum.Org.remove, "operatorId=" + organization.getOrgId() + "|desc=删除一条修改组织信息失败");
            }
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_WARN, null, "未选中组织");
        }
        return map;
    }

    /**
     * 选中某一个组织结构，跳转进入组织机构详细页面 <br/>
     * <p>
     * Description: 跳转进入组织机构详细页面 <br/>
     * <p>
     * Author: zhaosl<br/>
     * <p>
     * Date: 2013-4-25-上午10:56:45<br/>
     * <p>
     * 
     * @param request
     * @param response
     * @return
     * 
     */
    @RequestMapping("/toDetailView")
    public ModelAndView toDetailView()
    {
        ModelAndView mav = new ModelAndView("ac/org/org_view");
        String id = request.getParameter("id");

        if (StringUtils.isNotBlank(id))
        {
            Organization organization = null;
            try
            {
                organization = _organizationService.findById(new Long(id));
                addLog(ModuleEnum.Org.view, "operatorId=" + id + "|desc=查询一条修改组织信息成功");
            }
            catch (Exception e)
            {
                handleException(e);
                addLog(ModuleEnum.Org.view, "operatorId=" + id + "|desc=查询一条修改组织信息失败");
                mav.addObject("message", "操作失败");
                return mav;
            }
            mav.addObject("organization", organization);
            return mav;
        }
        else
        {
            mav.addObject("message", "Error:未选中树形中的组织");
            return mav;
        }
    }

    /*
     * (non-Javadoc) Description:操作日志记录 <br/>
     * 
     * @return
     * 
     * @see com.bcinfo.upp.admin.controller.AdminController#getMouduleCode()
     */
    public String getMouduleCode()
    {
        return ModuleEnum.Org.moduleName.value;
    }
}
